// ==UserScript==
// @name         青书学堂-自动刷课
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  青书学堂-自动刷课
// @author       twisly
// @match        *://*/*
// @icon         
// @grant        GM_setValue
// @grant        GM_getValue
// ==/UserScript==

(function () {
    'use strict';
    // 获取当前页面url
    var currPageUrl = window.location.href;

    // GM_setValue('idx', 0);
    // var doing = false, idx = 0, courseCnt = 36, watchTask = 0;
    var watchTask = 0;
    // var courseCnt = document.querySelectorAll('.level-2 .level-root a').length;
    var globalTask = setInterval(() => {
        var doing = GM_getValue('doing', false);
        var idx = GM_getValue('idx', 0);
        var courseCnt = 53;
        console.info( 'courseCnt: ' + courseCnt + ', idx: ' + idx)

        if (doing) {
            return;
        }

        // 课程列表页
        if (currPageUrl.indexOf("CourseStudy") > 0) {
            document.querySelectorAll('.level-2 .level-root a')[idx++].click();
        }

        // 课程播放页
        if (currPageUrl.indexOf("CourseShow") > 0) {
            if (document.querySelector('.vjs-big-play-button') != null) {
                var currentTime = document.querySelectorAll('.vjs-current-time-display')[0].innerText;
                var durationTime = document.querySelectorAll('.vjs-duration-display')[0].innerText;
                if (currentTime === durationTime) {
                    doing = false;
                    GM_setValue('doing', doing);
                    idx++;
                    GM_setValue('idx', idx);
                    console.info('currentTime: ' + currentTime + ", durationTime: " + durationTime + ', idx: ' + idx);
                    history.back();
                    return;
                }

                // 等待课程播放完
                if (watchTask > 0) {
                    return;
                }
                watchTask = setInterval(() => {
                    document.querySelectorAll('.vjs-big-play-button')[0].click();
                    doing = true;

                    currentTime = document.querySelectorAll('.vjs-current-time-display')[0].innerText;
                    durationTime = document.querySelectorAll('.vjs-duration-display')[0].innerText;
                    console.info('等待课程播放完, watchTask: ' + watchTask + ', 第' + idx + '讲 ' + currentTime + ' => ' + durationTime);
                    if (currentTime === durationTime) {
                        clearInterval(watchTask);
                        doing = false;
                        GM_setValue('doing', doing);
                        idx++;
                        GM_setValue('idx', idx);
                        history.back();

                        if (idx >= courseCnt) {
                            clearInterval(globalTask);
                        }
                    }
                }, 2000);
            }
        }
    }, 1000);
})();